"use strict";

/**
 * Web访问相关
 */
//------------------------------------------------------------------
import axios from "axios";
import util from "./vtuzx-util";
import { Toast } from 'vant';
//------------------------------------------------------------------

/**
 * 表示错误信息
 *
 * @param e 错误信息
 */
const $$showErrMsg = e => {
  Toast.fail(e.message || e.err || e);
};

/**
 * Web访问连接
 */
const $$api = axios.create({
  baseURL: process.env.VUE_APP_BASE_URL,
  timeout: 60000
});

/**
 * 标准调用处理
 *
 * @param opts 入参
 * @param config axios配置
 * @param callback 回调
 */
const $$request = async(opts, config, callback) => {
  if (opts.need_token) {
    let token = util.getStorage('token');
    if (!token) {
      document.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc86c4f92d2af5bab&redirect_uri=http%3A%2F%2Fmp.dlkehuan.com%2Fdlke_wap&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect";
      return callback({ data: { res: false, errMessage: "请重新Login"} });
    }
    if (config.headers) {
      config.headers.vt = token;
    } else {
      config.headers = { vt: token };
    }
  }
  config.url = "/" + (opts.apiVersion || process.env.VUE_APP_API_VERSION || '') + config.url;

  if (opts.responseType) config.responseType = opts.responseType;
  if (opts.timeout) config.timeout = opts.timeout;
  if (opts.onUploadProgress) config.onUploadProgress = opts.onUploadProgress;
  try {
    let result = await $$api(config);
    return callback(result);
  } catch(e) {
    return callback({ headers: {}, data: { res: false, errMessage: e.message || e.err || e } });
  }
};

/**
 * 标准返回处理
 *
 * @param opts 入参
 * @param config axios配置
 */
const $$return = async(opts, config) => {
  return $$request(opts, config, res => {
    if (res.data.res) {
      return res.data;
    }
    if (res.data.code && res.data.code === "E_not_login") {
      util.removeStorage('token');
      document.location.href = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxc86c4f92d2af5bab&redirect_uri=http%3A%2F%2Fmp.dlkehuan.com%2Fdlke_wap&response_type=code&scope=snsapi_userinfo&connect_redirect=1#wechat_redirect";
      return res.data;
    }
    if (!opts.silence) {
      $$showErrMsg(res.data.err);
    }
    return res.data;
  });
};

export default {
  /**
   * JSON方式访问API
   *
   * @param url 路由
   * @param data 参数
   * @param opts 默认配置
   */
  json(url, data = {}, opts) {
    let _opts = Object.assign({ silence: false, need_token: true }, opts);
    let config = {
      method: 'post',
      url,
      data,
      headers: { 'Content-Type': 'application/json;charset=utf-8' }
    };
    return $$return(_opts, config);
  },
  /**
   * URL直接方式访问API
   *
   * @param url 路由
   * @param params 参数
   * @param opts 默认配置
   *    need_token: true: 需要token, false: 不需要token
   *    silence: false: 显示错误消息, true: 不显示错误消息
   */
  redirect(url, params = {}, opts) {
    let _opts = Object.assign({ silence: true, need_token: false }, opts);
    let config = {
      method: 'get',
      url,
      params
    };
    return $$return(_opts, config);
  },
  /**
   * Form方式访问API
   *
   * @param url 路由
   * @param data 参数
   * @param opts 默认配置
   *    need_token: true: 需要token, false: 不需要token
   *    silence: false: 显示错误消息, true: 不显示错误消息
   */
  form(url, data = {}, opts) {
    let _opts = Object.assign({ silence: false, need_token: true }, opts);
    let config = {
      method: 'post',
      url,
      headers: { 'Content-Type': 'multipart/form-data' }
    };
    let form = new FormData();
    for (let key in data) {
      if (data[key] instanceof Array) {
        let dataList = data[key];
        for(let i = 0; i < dataList.length; i++) {
          form.append(key, dataList[i]);
        }
      } else {
        form.append(key, data[key]);
      }
    }
    config.data = form;
    return $$return(_opts, config);
  },
  /**
   * Download方式访问API
   *
   * @param url 路由
   * @param data 参数
   * @param opts 默认配置
   *    need_token: true: 需要token, false: 不需要token
   *    silence: false: 显示错误消息, true: 不显示错误消息
   *    manual: true: 手动下载, false: 自动下载
   */
  download(url, data = {}, opts) {
    let _opts = Object.assign({ silence: false, need_token: true, manual: false, responseType: 'blob', apiVersion: '' }, opts);
    let config = {
      method: 'post',
      url,
      data
    };
    return $$request(_opts, config, result => {
      let fileName = result.headers["vtuzx-filename"];
      if (fileName) {
        // 下载成功
        let res = { res: true, data: result.data, filename: decodeURIComponent(fileName) };
        if (opts.manual) {
          // 手动下载时处理
          return res;
        } else {
          util.download(res);
          return res;
        }
      } else {
        // 下载失败
        if (result.request) {
          return new Promise(resolve => {
            let reader = new FileReader();
            reader.onload = e => {
              let content = JSON.parse(e.target.result);
              if (!content.res && !_opts.silence) $$showErrMsg(content.err);
              resolve(content);
            };
            reader.readAsText(result.data);
          });
        } else {
          if (!result.data.res && !_opts.silence) $$showErrMsg(result.data.err);
          return result.data;
        }
      }
    });
  }
};
